<template>
  <base-layout>
    <div class="project-review-container">
      <!-- 左侧信息区域 -->
      <div class="info-section">
        <a-card class="info-card">
          <template #title>
            <div class="card-title">
              <a-button @click="handleBack">
                <template #icon><arrow-left-outlined /></template>
                返回
              </a-button>
              <h2>项目审批</h2>
            </div>
          </template>
          <div class="info-content" v-if="project">
            <div class="info-item">
              <span class="label">项目名称：</span>
              <span class="value">{{ project.name || '加载中...' }}</span>
              <a-tag v-if="project.course" color="blue" class="course-tag">{{ project.course }}</a-tag>
            </div>
            <div class="info-item">
              <span class="label">开始日期：</span>
              <span class="value">{{ project.startTime || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">组长：</span>
              <div class="value">{{ getLeaderName(project.leader) }}</div>
            </div>
            <div class="info-item">
              <span class="label">组员：</span>
              <div class="value">{{ getMembersNames(project.members) }}</div>
            </div>
            <div class="info-item description">
              <span class="label">项目描述：</span>
              <div class="value description-text">{{ project.comment || '无描述' }}</div>
            </div>
          </div>
          <a-skeleton v-else active :paragraph="{ rows: 4 }" />
        </a-card>

        <!-- 提交记录卡片 -->
        <a-card class="submissions-card">
          <template #title>
            <div class="card-title-with-actions">
              <span>提交记录</span>
              <div class="actions">
                <a-button type="primary" @click="approveAll">
                  <template #icon><check-outlined /></template>
                  全部通过
                </a-button>
                <a-button danger @click="rejectAll">
                  <template #icon><close-outlined /></template>
                  全部驳回
                </a-button>
              </div>
            </div>
          </template>
          
          <a-timeline>
            <template v-if="submissions">
              <a-timeline-item v-for="(record, index) in submissions" :key="record.id">
                <template #dot>
                  <check-circle-outlined v-if="record.reviewStatus === 'APPROVED'" style="color: #52c41a" />
                  <close-circle-outlined v-else-if="record.reviewStatus === 'REJECTED'" style="color: #ff4d4f" />
                  <clock-circle-outlined v-else style="color: #1890ff" />
                </template>
                <div class="timeline-content">
                  <div class="timeline-header">
                    <span class="timeline-title">{{ record.type }}</span>
                    <span class="timeline-time">{{ record.submissionTime }}</span>
                    <a-tag 
                      :color="getStatusColor(record.reviewStatus)" 
                      class="status-tag"
                    >
                      {{ getStatusText(record.reviewStatus) }}
                    </a-tag>
                  </div>
                  <div class="timeline-desc">{{ record.description }}</div>
                  
                  <!-- 文件列表 -->
                  <div class="timeline-files" v-if="record.files">
                    <div class="file-item" v-for="(file, index) in record.files" :key="index">
                      <file-outlined class="file-icon" />
                      <span class="file-name">{{ file.originalFileName }}</span>
                      <div class="file-actions">
                        <eye-outlined class="preview-icon" @click="handleFilePreview(file)" />
                        <download-outlined class="download-icon" @click="handleFileDownload(file)" />
                      </div>
                    </div>
                  </div>
                  
                  <!-- 审批评论 -->
                  <div class="review-comment" v-if="record.reviewResult">
                    <div class="comment-header">审批意见：</div>
                    <div class="comment-content">{{ record.reviewResult }}</div>
                  </div>
                  
                  <!-- 审批操作 -->
                  <div class="review-actions" v-if="record.reviewStatus === 'PENDING'">
                    <a-textarea
                      v-model:value="record.tempComment"
                      placeholder="请输入审批意见（可选）"
                      :rows="2"
                      :maxLength="200"
                      show-count
                    />
                    <div class="action-buttons">
                      <a-button type="primary" @click="approveSubmission(index)">
                        <template #icon><check-outlined /></template>
                        通过
                      </a-button>
                      <a-button danger @click="rejectSubmission(index)">
                        <template #icon><close-outlined /></template>
                        驳回
                      </a-button>
                    </div>
                  </div>
                </div>
              </a-timeline-item>
            </template>
            <template v-else>
              <a-empty description="暂无提交记录" />
            </template>
          </a-timeline>
        </a-card>
      </div>

      <!-- 右侧统计区域 -->
      <div class="stats-section">
        <a-card class="stats-card">
          <template #title>
            <div class="card-title">审批统计</div>
          </template>
          <div class="stats-content">
            <div class="stat-item">
              <div class="stat-label">总提交数</div>
              <div class="stat-value">{{ submissions?.length || 0 }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">已通过</div>
              <div class="stat-value approved">{{ getApprovedCount() }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">已驳回</div>
              <div class="stat-value rejected">{{ getRejectedCount() }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">待审批</div>
              <div class="stat-value pending">{{ getPendingCount() }}</div>
            </div>
          </div>
          
          <a-divider />
          
          <div class="project-status">
            <div class="status-label">项目状态</div>
            <a-progress 
              :percent="getProjectProgress()" 
              :status="getProjectProgressStatus()"
            />
          </div>
        </a-card>
        
        <!-- 文件预览弹窗 -->
        <a-modal
          v-model:visible="previewVisible"
          :title="previewFile?.name"
          :footer="null"
          width="800px"
          @cancel="closePreview"
        >
          <div class="preview-content">
            <!-- 图片预览 -->
            <img
              v-if="isImageFile(previewFile)"
              :src="previewFile?.previewUrl"
              class="preview-image"
              alt="预览图片"
            />
            <!-- PDF预览 -->
            <iframe
              v-else-if="isPdfFile(previewFile)"
              :src="previewFile?.previewUrl"
              class="preview-pdf"
            ></iframe>
            <!-- 其他文件类型 -->
            <div v-else class="preview-unsupported">
              <file-outlined class="unsupported-icon" />
              <p>该文件类型暂不支持预览，请下载后查看</p>
              <a-button type="primary" @click="handleFileDownload(previewFile)">
                下载文件
              </a-button>
            </div>
          </div>
        </a-modal>
      </div>
    </div>
  </base-layout>
</template>

<script>
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import BaseLayout from '@/components/layout/BaseLayout.vue'
import { 
  ArrowLeftOutlined,
  FileOutlined, 
  CheckOutlined,
  CloseOutlined,
  EyeOutlined,
  DownloadOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined
} from '@ant-design/icons-vue'
import {reviewSubmission} from "@/api/assignment.js";
import {useAssignmentReview} from "@/composables/useAssignmentReview.js";

export default {
  name: 'ProjectReview',
  components: {
    BaseLayout,
    ArrowLeftOutlined,
    FileOutlined,
    CheckOutlined,
    CloseOutlined,
    EyeOutlined,
    DownloadOutlined,
    CheckCircleOutlined,
    CloseCircleOutlined,
    ClockCircleOutlined
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const { project, submissions, refreshData, userOptions } = useAssignmentReview()
    
    // Debug
    console.log('Component mounted - current project:', project.value)
    watch(project, (newProject) => {
      console.log('Project changed:', newProject)
    })
    
    const previewVisible = ref(false)
    const previewFile = ref(null)

    // 获取组长姓名
    const getLeaderName = (leaderId) => {
      if (!leaderId || !userOptions.value) return '未指定'
      const leader = userOptions.value.find(user => user.value === leaderId)
      return leader ? leader.label : '未知用户'
    }
    
    // 获取组员姓名列表
    const getMembersNames = (memberIds) => {
      if (!memberIds || !Array.isArray(memberIds) || !userOptions.value) return '无'
      return memberIds
        .map(id => {
          const member = userOptions.value.find(user => user.value === id)
          return member ? member.label : '未知用户'
        })
        .join('、')
    }
    
    // 获取状态颜色
    const getStatusColor = (status) => {
      const colors = {
        'APPROVED': 'success',
        'REJECTED': 'error',
        'PENDING': 'processing'
      }
      return colors[status] || 'default'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const texts = {
        'APPROVED': '已通过',
        'REJECTED': '已驳回',
        'PENDING': '待审批'
      }
      return texts[status] || '未知状态'
    }
    
    // 获取通过数量
    const getApprovedCount = () => {
      if (!submissions?.value) return 0;
      return submissions.value.filter(r => r.reviewStatus === 'APPROVED').length
    }
    
    // 获取驳回数量
    const getRejectedCount = () => {
      if (!submissions?.value) return 0;
      return submissions.value.filter(r => r.reviewStatus === 'REJECTED').length
    }
    
    // 获取待审批数量
    const getPendingCount = () => {
      if (!submissions?.value) return 0;
      return submissions.value.filter(r => r.reviewStatus === 'PENDING').length
    }
    
    // 计算项目总进度
    const getProjectProgress = () => {
      if (!submissions?.value) return 0;
      const total = submissions.value.length
      if (total === 0) return 0
      return Math.round((getApprovedCount() / total) * 100)
    }
    
    // 获取项目进度状态
    const getProjectProgressStatus = () => {
      if (!submissions?.value) return 'normal';
      if (getRejectedCount() > 0) return 'exception'
      if (getApprovedCount() === submissions.value.length) return 'success'
      return 'active'
    }
    
    // 通过单个提交
    const approveSubmission = async (index) => {
      const record = submissions.value[index]
      if (!project.value || !project.value.id) {
        message.error('项目信息加载失败，无法审批')
        return
      }
      
      try {
        const requestBody = {
          reviewerId: localStorage.getItem('userId'),
          reviewResult: record.tempComment || '',
          action: 'APPROVE'
        }
        await reviewSubmission(project.value.id, record.id, requestBody)
        message.success(`已通过「${record.type}」的提交`)
        await refreshData()
      } catch (error) {
        console.error('审批失败:', error)
        message.error('审批失败: ' + (error.message || '未知错误'))
      }
    }
    
    // 驳回单个提交
    const rejectSubmission = async (index) => {
      const record = submissions.value[index]
      if (!project.value || !project.value.id) {
        message.error('项目信息加载失败，无法驳回')
        return
      }
      
      if (!record.tempComment?.trim()) {
        message.error('驳回时请填写审批意见')
        return
      }
      
      try {
        const requestBody = {
          reviewerId: localStorage.getItem('userId'),
          reviewResult: record.tempComment,
          action: 'REJECT'
        }
        await reviewSubmission(project.value.id, record.id, requestBody)
        message.success(`已驳回「${record.type}」的提交`)
        await refreshData()
      } catch (error) {
        console.error('驳回失败:', error)
        message.error('驳回失败: ' + (error.message || '未知错误'))
      }
    }
    
    // 全部通过
    const approveAll = async () => {
      if (!submissions.value || !project.value || !project.value.id) {
        message.error('项目信息加载失败，无法批量审批')
        return;
      }
      
      let count = 0
      const promises = []
      
      for (const record of submissions.value) {
        if (record.reviewStatus === 'PENDING') {
          const requestBody = {
            reviewerId: localStorage.getItem('userId'),
            reviewResult: record.tempComment || '批量通过',
            action: 'APPROVE'
          }
          promises.push(reviewSubmission(project.value.id, record.id, requestBody))
          count++
        }
      }
      
      if (count > 0) {
        try {
          await Promise.all(promises)
          message.success(`已通过 ${count} 个待审批项`)
          await refreshData()
        } catch (error) {
          console.error('批量审批失败:', error)
          message.error('批量审批失败: ' + (error.message || '未知错误'))
        }
      } else {
        message.info('没有待审批项')
      }
    }
    
    // 全部驳回
    const rejectAll = async () => {
      if (!submissions.value || !project.value || !project.value.id) {
        message.error('项目信息加载失败，无法批量驳回')
        return;
      }
      
      let count = 0
      const promises = []
      
      for (const record of submissions.value) {
        if (record.reviewStatus === 'PENDING') {
          const requestBody = {
            reviewerId: localStorage.getItem('userId'),
            reviewResult: record.tempComment || '批量驳回',
            action: 'REJECT'
          }
          promises.push(reviewSubmission(project.value.id, record.id, requestBody))
          count++
        }
      }
      
      if (count > 0) {
        try {
          await Promise.all(promises)
          message.success(`已驳回 ${count} 个待审批项`)
          await refreshData()
        } catch (error) {
          console.error('批量驳回失败:', error)
          message.error('批量驳回失败: ' + (error.message || '未知错误'))
        }
      } else {
        message.info('没有待审批项')
      }
    }
    
    // 返回上一页
    const handleBack = () => {
      router.back()
    }
    
    // 文件预览
    const handleFilePreview = (file) => {
      previewFile.value = {...file,
        previewUrl: `/storage/${file.storedFileName}`,
        name: file.originalFileName,
        url: file.filePath,
        type: file.fileType
      }
      previewVisible.value = true
    }
    
    // 关闭预览
    const closePreview = () => {
      previewVisible.value = false
      previewFile.value = null
    }
    
    // 文件下载
    const handleFileDownload = (file) => {
      window.open(file.previewUrl, '_blank')
      message.success(`开始下载文件：${file.originalFileName}`)
    }
    
    // 判断是否为图片文件
    const isImageFile = (file) => {
      return file && file.type && file.type.startsWith('image/')
    }
    
    // 判断是否为PDF文件
    const isPdfFile = (file) => {
      return file && file.type && file.type === 'application/pdf'
    }
    
    return {
      project,
      submissions,
      previewVisible,
      previewFile,
      getLeaderName,
      getMembersNames,
      getStatusColor,
      getStatusText,
      getApprovedCount,
      getRejectedCount,
      getPendingCount,
      getProjectProgress,
      getProjectProgressStatus,
      approveSubmission,
      rejectSubmission,
      approveAll,
      rejectAll,
      handleBack,
      handleFilePreview,
      handleFileDownload,
      closePreview,
      isImageFile,
      isPdfFile
    }
  }
}
</script>

<style scoped>
.project-review-container {
  padding: 24px;
  min-height: calc(100vh - 64px);
  background: #f0f2f5;
  display: flex;
  gap: 24px;
}

.info-section {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.stats-section {
  width: 380px;
  flex-shrink: 0;
}

.info-card,
.submissions-card,
.stats-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  display: flex;
  align-items: center;
  gap: 16px;
}

.card-title h2 {
  margin: 0;
  font-size: 18px;
}

.card-title-with-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions {
  display: flex;
  gap: 8px;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  line-height: 24px;
}

.info-item .label {
  color: #8c8c8c;
  min-width: 80px;
}

.info-item .value {
  flex: 1;
}

.course-tag {
  margin-left: 8px;
}

.description {
  align-items: flex-start;
}

.description-text {
  white-space: pre-wrap;
  line-height: 1.6;
}

.stats-card {
  position: sticky;
  top: 24px;
}

.stats-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
}

.stat-label {
  color: #8c8c8c;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 500;
  color: #262626;
}

.stat-value.approved {
  color: #52c41a;
}

.stat-value.rejected {
  color: #ff4d4f;
}

.stat-value.pending {
  color: #1890ff;
}

.project-status {
  margin-top: 16px;
}

.status-label {
  margin-bottom: 8px;
  color: #262626;
}

.timeline-content {
  background: #f9f9f9;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.timeline-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.timeline-title {
  font-weight: 500;
  color: #262626;
  margin-right: 12px;
}

.timeline-time {
  color: #8c8c8c;
  font-size: 14px;
  margin-right: 12px;
}

.status-tag {
  margin-left: auto;
}

.timeline-desc {
  margin-bottom: 12px;
  line-height: 1.6;
}

.timeline-files {
  margin-top: 12px;
  margin-bottom: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
}

.file-icon {
  color: #8c8c8c;
  margin-right: 8px;
}

.file-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.preview-icon,
.download-icon {
  color: #1890ff;
  cursor: pointer;
  padding: 4px;
}

.preview-icon:hover,
.download-icon:hover {
  color: #40a9ff;
}

.review-comment {
  margin-top: 12px;
  padding: 12px;
  background: #f0f7ff;
  border-radius: 4px;
  border-left: 3px solid #1890ff;
}

.comment-header {
  font-weight: 500;
  color: #1890ff;
  margin-bottom: 4px;
}

.comment-content {
  line-height: 1.6;
}

.review-actions {
  margin-top: 16px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  margin-top: 8px;
  justify-content: flex-end;
}

.preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: #f0f2f5;
  border-radius: 4px;
  padding: 16px;
}

.preview-image {
  max-width: 100%;
  max-height: 600px;
  object-fit: contain;
}

.preview-pdf {
  width: 100%;
  height: 600px;
  border: none;
}

.preview-unsupported {
  text-align: center;
  padding: 32px;
}

.unsupported-icon {
  font-size: 48px;
  color: #8c8c8c;
  margin-bottom: 16px;
}

@media screen and (max-width: 1200px) {
  .project-review-container {
    flex-direction: column;
  }

  .stats-section {
    width: 100%;
  }

  .stats-card {
    position: static;
  }
  
  .stats-content {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media screen and (max-width: 768px) {
  .stats-content {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style> 